import { ApprovalWidth, useApproval, useApprovalProvide } from './approval-helper';

// import { CurrentApprovalList, HistoryApprovalList, useApprovalHistory } from './components/Progress';
// 暂不引入历史
import { CurrentApprovalList } from './components/Progress';
// import { ProcessWrapper } from '@/components/business';
// import { vitalConfigProvideKey } from 'vital';
import { MciDrawer/** , MciTabPane, MciTabs */ } from '@/components/base';
// import { ApprovalFooter } from './components/Footer';
import './index.scss';
import { PropType, Teleport } from 'vue';
import { useDrawerSize } from '../DrawerRouter';
import { px2Rem } from '@/utils/rem';
// import { useEditorSelection } from '@/components/complex/RichEditor/utils/useSelection';
// import { useMobileApproveTab } from '@/views/app';
// import { MobileApproval } from './components/MobileApproval';
// export { BatchApproval } from './components/Batch';

type TTimeType = 'current' | 'history';
// 审批组件
const Approval = defineComponent({
  name: 'Approval',
  props: {
    class: {
      type: String,
      default: ''
    },
    navWidth: {
      type: String,
      default: ''
    },
    hasProvide: {
      type: Boolean,
      default: true
    },
    // 审批实例id
    processInst: {
      type: String,
      default: ''
    },
    /* 审批完成后 刷新审批组件 ｜ 关闭页面 */
    completeHandleType: {
      type: String as PropType<'refresh' | 'close'>,
      default: 'close'
    }
  },
  emits: ['update:navWidth', 'loaded'],
  setup(props, { emit }) {
    const { processInst } = toRefs(props);
    const handleInit = () => {
      emit('loaded');
    };
    const {
      hasApproval: approvalVisible,
      navWidth,
      approvalMode,
      isSubmitUser,
      isApprovalUser,
      businessKey,
      loading,
      isAllow,
      taskId
    } = props.hasProvide ? useApproval(handleInit, processInst, props.completeHandleType) : useApprovalProvide();

    // const { historyLoading, historyData, getApprovalHistory } = useApprovalHistory();

    // const { initSelection } = useEditorSelection();
    const type = ref<TTimeType>('current');

    // 抽屉
    const drawerVisible = ref(false);
    const drawerRef = ref<InstanceType<typeof MciDrawer>>();
    const drawerWidth = px2Rem('784px');
    const handleDrawer = (visible: boolean) => {
      if (!visible) {
        drawerRef.value?.beforeCloseHandle(() => {});
      }
      drawerVisible.value = visible;
      // initSelection();
    };

    // const approvalFooterRef = ref<InstanceType<typeof ApprovalFooter>>();
    // 高度限制
    const contentStyles = computed(() => {
      return {
        // height: 'calc(100vh - 300px)'
      };
    });

    watch(navWidth, () => {
      emit('update:navWidth', navWidth.value);
    });

    return {
      approvalVisible,
      approvalMode,
      contentStyles,
      type,
      // historyData,
      // historyLoading,
      isSubmitUser,
      isApprovalUser,
      drawerVisible,
      drawerWidth,
      drawerRef,
      businessKey,
      loading,
      // approvalFooterRef,
      // getApprovalHistory,
      handleDrawer,
      ...useDrawerSize(),
      isAllow,
      taskId
    };
  },
  render() {
    if (!this.approvalVisible) return null;

    const renderInnerContent = () => {
      const isFull = this.drawerVisible;
      // 全屏按钮
      const renderFullScreen = () => {
        if (isFull) {
          return null;
        }
        return (
          <span
            class="mci-icon-a-fullscreen absolute right-0  cursor-pointer"
            onClick={() => {
              this.handleDrawer(true);
            }}></span>
        );
      };

      const className = isFull ? 'top-0 left-0 sticky bg-white z-1000' : 'relative';
      return (
        <div
          v-loading={this.loading}
          class={`flex flex-col h-full approval-inner-container ${isFull ? 'bd p-16 rounded-8' : ''}`}>
          {/* <div class={className}>
            <MciTabs
              v-model={this.type}
              type="normal"
              before-leave={(type: string) => {
                this.getApprovalHistory(type, this.businessKey + '');
              }}>
              <MciTabPane label={'当前审批'} name="current" />
              <MciTabPane label={'审批历史'} name="history" />
            </MciTabs>
            {renderFullScreen()}
          </div> */}
          <div class="flex-1 overflow-y-scroll">
            {this.type === 'current' ? (
              <>
                {/* <CurrentApprovalList handleReply={this.approvalFooterRef?.handleReply} /> */}
                <CurrentApprovalList />
              </>
            ) : (
              <></>
              // <HistoryApprovalList list={this.historyData} loading={this.historyLoading} />
            )}
          </div>
          {/* {this.type === 'current' ? (
            <ApprovalFooter
              ref="approvalFooterRef"
              completeHandleType={this.completeHandleType}
              drawerVisible={this.drawerVisible}
            />
          ) : null} */}
        </div>
      );
    };
    const createDrawerContainer = () => {
      const createCloseIcon = () => {
        if (this.drawerVisible) {
          return (
            <span
              class="mci-icon-close1 close-icon text-22px absolute right-28px top-18px z-10000"
              onClick={() => {
                this.handleDrawer(false);
              }}></span>
          );
        }
      };
      return (
        <div class={`h-full bg-white ${this.drawerVisible ? 'p-y-16px relative ' : ''}`}>
          <div class="m-auto h-full relative " style={{ width: this.drawerVisible ? this.drawerWidth : '' }}>
            {renderInnerContent()}
          </div>
          {createCloseIcon()}
        </div>
      );
    };
    return (
      <>
        <Teleport to="body">
          <MciDrawer
            ref="drawerRef"
            v-model={this.drawerVisible}
            with-header={false}
            size={this.compSize}
            custom-class="approval-full-model"></MciDrawer>
        </Teleport>
        <div class={`${this.class} `} style={{ width: ApprovalWidth, border:'solid 0px green' }}>
          <div class={`top-0 right-0 sticky  overflow-y-scroll p-1 px-16 rounded-8 approval`} style={this.contentStyles}>
            {/* 放大时，将内容插入 到抽屉中，保持输入框的状态 */}
            <Teleport to=".approval-full-model" disabled={!this.drawerVisible}>
              {createDrawerContainer()}
            </Teleport>
          </div>
        </div>
      </>
    );
  }
});

/**
 * 等待审批组件加载完成后，加载 内容组件
 */
// const RenderApprovalContent = defineComponent({
//   props: {
//     hasProvide: {
//       type: Boolean,
//       default: true
//     },
//     // 审批实例id
//     processInst: {
//       type: String,
//       default: ''
//     },
//     /* 审批完成后 刷新审批组件 ｜ 关闭页面 */
//     completeHandleType: {
//       type: String as PropType<'refresh' | 'close'>,
//       default: 'close'
//     }
//   },
//   emits: ['loaded'],
//   setup(props, { slots, emit }) {
//     const { processInst } = toRefs(props);
//     const handleInit = () => {
//       emit('loaded');
//     };
//     const { isApp, mobileApproveTab } = useMobileApproveTab();

//     const { isComplete } = props.hasProvide
//       ? useApproval(handleInit, processInst, isApp ? 'refresh' : props.completeHandleType)
//       : useApprovalProvide();

//     return () => {
//       if (isApp && mobileApproveTab.isHideApprove === false) {
//         return (
//           <div class="flex flex-nowrap h-full w-full">
//             {mobileApproveTab.active === 'approve' ? (
//               <MobileApproval class="ml-24 shrink-0 w-full" hasProvide={false} />
//             ) : (
//               <div class="flex-1 min-w-0">{slots.default?.()}</div>
//             )}
//           </div>
//         );
//       }
//       return (
//         <div class="flex flex-nowrap w-full">
//           <div class="flex-1 min-w-0">{isComplete.value ? slots.default?.() : ''}</div>
//           <Approval class="ml-24 shrink-0" hasProvide={false} />
//         </div>
//       );
//     };
//   }
// });

// const ApprovalWrapper = defineComponent({
//   name: 'ApprovalWrapper',
//   setup() {
//     const { detailMode } = useApproval();
//     const vitalConfig = reactive({
//       formMode: detailMode.value
//     });
//     provide(vitalConfigProvideKey, vitalConfig);
//     watch(detailMode, () => {
//       vitalConfig.formMode = detailMode.value;
//     });
//     return {
//       detailMode
//     };
//   },
//   render() {
//     const contentSlot = () => <RenderApprovalContent hasProvide={false}>{this.$slots.default?.()}</RenderApprovalContent>;
//     const viewFooterSlot = () => <>{this.$slots.viewFooter?.()}</>;
//     return <ProcessWrapper vSlots={{ default: contentSlot, viewFooter: viewFooterSlot }} />;
//   }
// });

export { Approval, /** ApprovalWrapper, RenderApprovalContent, **/ useApproval, useApprovalProvide };
